
import {Row,Col,Table, Button, Tag, Popconfirm,Avatar , Modal,Form,Input, Select ,message  } from "antd"
import {useState,useEffect,useRef} from "react"
import {ajax} from "@/services"
import { roleList } from '@/utils';
import { baseURL } from '@/services/request';
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  CaretDownOutlined,
  UserOutlined,
  PoweroffOutlined,
  ExclamationCircleOutlined,
  VideoCameraOutlined,
  UploadOutlined, LockOutlined , WhatsAppOutlined , MobileOutlined,PhoneOutlined , AppstoreOutlined 
} from '@ant-design/icons';

import {observer} from "mobx-react"
import info from "@/mobx/info"
const { Option } = Select;
const tailLayout1 = {
  wrapperCol:{
      span:14,
      offset:0
  }
}
export default observer(function UserList(){
  const [list,setList] = useState<Array<object>>([])
  const [obj,setObj] = useState<object>({})
  const [visible,setVisible] = useState<boolean>(false)
  const [role,setRole] = useState<number>(0)
  const {userInfo} = info;
  const uform:any = useRef()
  const keywordInp:any = useRef()

  useEffect( ()=>{
    getUserListAction({})
  },[])
  const changeSelectRole = (value)=>{
    console.log(value); 
    setRole(value);  
  }
  const handleSearch = ()=>{
    console.log(keywordInp)
     var keyword = keywordInp.current.state.value;
     getUserListAction({
       role,
       keyword
     })
  }
  const getUserListAction = async (options:any)=>{
    let res = await ajax.getuserlist(options);
    const {code,result} = res;
    if(code==200){
      setList(result)
    }
  }
  const columns = [
    {
      title: '#',
      align:"center",
      render:(value,item,index)=>{
        return index+1
      }
    },
    {
      title: '姓名',
      align:"center",
      dataIndex: 'username',
      key: 'name',
    },
    {
      title: '头像',
      align:"center",
      render:(item,value,index)=>{
        return (
          item.avatar ?
            <Avatar style={{cursor:"pointer"}}  src={item.avatar.replace(/public/,baseURL)} />:
            <Avatar style={{cursor:"pointer"}} icon={<UserOutlined />} />
        )
      }
    },
    {
      title: '身份',
      align:"center",
      render:(item,value,index)=>{
        return (
          <Tag  color={roleList.find(v=>v.value==item.role).color}> {roleList.find(v=>v.value==item.role).text } </Tag>
        )
      }
    },
    {
      title: '手机号码',
      align:"center",
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title:"操作",
      align:"center",
      render:(item,value,index)=>{
        return (
          userInfo?
          <div>
            <Popconfirm
              title="你确定要删除吗?"
              onConfirm={()=>onConfirm(item,index)}
              onCancel={onCancel}
              okText="确定"
              cancelText="不"
              disabled={ userInfo.role <= item.role} 
            >
              <Button type="primary"  disabled={ userInfo.role <= item.role} size="small" danger style={{margin:"4px"}}>删除</Button>
            </Popconfirm>
            {/* item.role  userInfo.role  */}
            <Button onClick={()=>handleChangeItem(item,index)} disabled={ userInfo.role <= item.role} style={{margin:"4px"}} type="primary" size="small"  >修改</Button>
          </div>
          :null
        )
      }
    }
  ]
  const onConfirm = async (item,index)=>{
    console.log(item)
    console.log(index);
    let res = await ajax.deloneuser({_id:item._id})
    const {code,result} = res;
    if(code==200){
      // 删除前端
      list.splice(index,1)
      setList([...list])
    }
  }
  const onCancel = ()=>{

  }
  const handleChangeItem = (item,index)=>{
      setVisible(true)
      console.log(uform)
      // uform.current.
      setTimeout(()=>{
        item.index = index; 
        setObj(item);  // 存储中间数据 要修改的数据 
        uform.current.setFieldsValue(item);
      },300)
  }
  const handleOk = ()=>{
      // 点击了确定修改 
      uform.current.validateFields()
      .then(async value=>{
        console.log(value)
        console.log(obj)
        let {code,result} = await ajax.updateoneuser({
          _id:obj._id,
          ...value
        })
        if(code==200){
          list.splice(obj.index,1,{...obj,...value})
          setList([...list])
          setVisible(false)
        }
      })
      .catch(err=>{
        message.error("请填写要修改的数据 ")
      })
  }
  const handleCancel = ()=>{
    setVisible(false)
  }
  const onFinish = ()=>{

  }

  const onFinishFailed = ()=>{

  }
  return (
    <div>
      <h1> 用户列表  </h1>
      <Row style={{marginTop:10,marginBottom:10}}>
        <Col span={5}>
            <Input placeholder="请输入搜索关键字" ref={keywordInp} />
        </Col>
        <Col span={5} style={{margin:"0 10px"}}>
          <Select onChange={changeSelectRole}  style={{width:'100%'}} placeholder="请选择">
            {
              roleList.map((l,i)=>{
                return (
                  <Option key={i} value={l.value}>
                  {l.text}
                </Option>
                )
              })
            }
          </Select>
        </Col>
        <Col>
          <Button onClick={handleSearch} type="primary" danger>点击搜索</Button>
        </Col>
      </Row>
      <Row>
        <Col span={22} offset={0}>
          <Table 
            dataSource={list}
            columns={columns}
            sticky
            bordered
            id="table"
            rowKey={item=>item._id}
            pagination={{pageSize:6}}
          >
          </Table>   
        </Col>
      </Row>

      <Modal
         title="修改用户" 
        visible={visible} 
        onOk={handleOk} 
        onCancel={handleCancel}
        cancelText="取消"
        okText="确认修改"
        >
          <Form
            name="basic"
            initialValues={{ }}
            autoComplete="off"
            className="login-form"
            ref={uform}
            layout={'vertical'}
          >
               <Form.Item
                  {...tailLayout1}
                  name="phone"
                  label="手机号码"
                  rules={[
                    { required: true, message: '请输入你的手机号码' }
                  ]}
                >
                  <Input disabled prefix={<PhoneOutlined className="site-form-item-icon" />} placeholder="请输入你的手机号码" />
              </Form.Item>
              <Form.Item
                {...tailLayout1}
                  name="username"
                  label="用户名称"
                  rules={[{ required: true, message: '请输入你的用户名' }]}
                >
                  <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入你的用户名" />
              </Form.Item>
              <Form.Item
                {...tailLayout1}
                  name="role"
                  label="用户身份"
                  rules={[{ required: true, message: '请输入你的用户名' }]}
                >
                  {userInfo?<Select>
                      {
                        roleList.map((l,i)=>{
                          return (
                            (userInfo.role > l.value) ?<Option key={i} value={l.value}>
                              {l.text}
                            </Option>
                            :null 
                          )
                        })
                      }
                  </Select>:null}
              </Form.Item>
          </Form>
      </Modal>
    </div>
  )
})